package cn.xsly.ymcc.service.impl;

import cn.xsly.ymcc.constants.Constants;
import cn.xsly.ymcc.domain.MessageBlacklist;
import cn.xsly.ymcc.mapper.MessageBlacklistMapper;
import cn.xsly.ymcc.result.JSONResult;
import cn.xsly.ymcc.service.IMessageBlacklistService;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author whale
 * @since 2022-10-30
 */
@Service
public class MessageBlacklistServiceImpl extends ServiceImpl<MessageBlacklistMapper, MessageBlacklist> implements IMessageBlacklistService {
    @Autowired
    private RedisTemplate redisTemplate;

    public Boolean selectByIpAndPhone(String ip, String phone) {
        //false存在，true不存在
        Boolean status = false;
        String a = (String) redisTemplate.opsForValue().get(Constants.BLACKLIST_IP + ip);
        String b = (String) redisTemplate.opsForValue().get(Constants.BLACKLIST_PHONE + phone);
        if (a == null && b == null) {
            status = true;
            try {
                Wrapper<MessageBlacklist> wrapper = new EntityWrapper<>();
                wrapper.eq("ip", ip);
                wrapper.eq("phone", phone);
                MessageBlacklist messageBlacklist = selectOne(wrapper);
                String ip1 = messageBlacklist.getIp();
                String phone1 = messageBlacklist.getPhone();


                if (ip1 != null && phone1 != null) {
                    redisTemplate.opsForValue().set(Constants.BLACKLIST_IP + ip, ip1, 30, TimeUnit.MINUTES);
                    redisTemplate.opsForValue().set(Constants.BLACKLIST_PHONE + phone, phone1, 30, TimeUnit.MINUTES);
                    status = false;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return true;
        }
        return status;
    }

    @Override
    public void deleteBlackList(MessageBlacklist blacklist) {
        super.deleteById(blacklist.getId());
        redisTemplate.delete(Constants.BLACKLIST_IP + blacklist.getIp());
        redisTemplate.delete(Constants.BLACKLIST_PHONE + blacklist.getPhone());
    }
}
